<template>
	<view class="wrap">
		<view class="key-input">
			<view class="title">输入验证码</view>
			<view class="tips">验证码已发送至 {{phone}}</view>
			<u-message-input :focus="true" :value="value" @change="change" @finish="finish" mode="bottomLine"
				:maxlength="maxlength" width='70'></u-message-input>
			<text :class="{ error: error }">验证码错误，请重新输入</text>
			<view class="captcha">
				<text :class="{ noCaptcha: show }" @tap="noCaptcha">收不到验证码点这里</text>
				<text :class="{ regain: !show }">{{ second }}秒后重新获取验证码</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				maxlength: 6,
				value: '',
				second: 60,
				show: false,
				error: false,
				phone: '',
				guid: ''
			};
		},
		computed: {},
		onLoad(options) {
			this.phone = options.phone
			this.guid = options.guid
			const _intervalId = setInterval(() => {
				this.second--
				if (this.second === 0) {
					this.show = true
					clearInterval(_intervalId)
				}
			}, 1000)
		},
		methods: {
			// 收不到验证码选择时的选择
			noCaptcha() {
				uni.showActionSheet({
					itemList: ['重新获取验证码', '更换手机号登录', '账号密码登录'],
					success: (res) => {
						if (res.tapIndex !== 0) {
							this.$u.route({
								type: 'redirect',
								url: 'pages/users/sign-in'
							})
						} else {
							this.guid = this.$u.guid()
							this.$u.api.sendLoginCaptcha({
								phone: this.phone,
								uuid: this.guid
							}).then(res => {
								this.second = 60
								this.show = false
								this.$u.toast('发送成功')
							}).catch(err => {
								console.error(err)
							})
						}
					}
				});
			},
			// change事件侦听
			change(value) {
				// console.log('change', value);
			},
			// 输入完验证码最后一位执行
			finish(value) {
				// console.log('finish', value);
				this.$u.api.signIn('sms', {
					account: this.phone,
					password: value,
					uuid: this.guid
				}).then(res => {
					this.$u.vuex('vuex_token', res.token)
					this.$u.api.getCurrentUser().then(res => {
						this.$u.vuex('vuex_user', res)
						if (!this.$store.state.socket_state) {
							this.$socket.initWebSocket()
						}
						// console.log(res)
						this.$u.route({
							type: 'tab',
							url: 'pages/home/home'
						})
					}).catch(err => {
						console.error(err)
					})
				}).catch(err => {
					console.error(err)
				})
			}
		}
	};
</script>

<style lang="scss" scoped>
	.wrap {
		padding: 80rpx;
	}

	.box {
		margin: 30rpx 0;
		font-size: 30rpx;
		color: 555;
	}

	.key-input {
		padding: 30rpx 0;

		text {
			display: none;
		}

		.error {
			display: block;
			color: red;
			font-size: 30rpx;
			margin: 20rpx 0;
		}
	}

	.title {
		font-size: 50rpx;
		color: #333;
	}

	.key-input .tips {
		font-size: 30rpx;
		color: #333;
		margin-top: 20rpx;
		margin-bottom: 60rpx;
	}

	.captcha {
		color: $u-type-warning;
		font-size: 30rpx;
		margin-top: 40rpx;

		.noCaptcha {
			display: block;
		}

		.regain {
			display: block;
		}
	}
</style>
